#include "tcpserver.h"
#include <QDebug>

TcpServer::TcpServer(QObject *parent) : QObject(parent)
{
    m_server = new QTcpServer(this);

    // 连接“新客户端连接”信号到自定义槽函数
    connect(m_server, &QTcpServer::newConnection, this, &TcpServer::slotNewConnection);
}

TcpServer::~TcpServer()
{
    // 关闭所有客户端连接并释放资源
    for (QTcpSocket *socket : m_clientSockets) {
        socket->close();
        socket->deleteLater();
    }
    m_server->close();
}

bool TcpServer::startServer(quint16 port)
{
    // 监听指定端口（任意IP）
    if (m_server->listen(QHostAddress::Any, port)) {
        qDebug() << "Server started on port" << port;
        return true;
    } else {
        qDebug() << "Server start failed: " << m_server->errorString();
        return false;
    }
}

void TcpServer::slotNewConnection()
{
    // 获取新连接的客户端套接字
    QTcpSocket *clientSocket = m_server->nextPendingConnection();
    if (clientSocket) {
        m_clientSockets.append(clientSocket);

        // 连接“数据可读”和“断开连接”信号到对应槽函数
        connect(clientSocket, &QTcpSocket::readyRead, this, &TcpServer::slotReadyRead);
        connect(clientSocket, &QTcpSocket::disconnected, this, &TcpServer::slotDisconnected);

        // 发射“客户端连接”信号
        QString clientAddr = clientSocket->peerAddress().toString() + ":" +
                             QString::number(clientSocket->peerPort());
        emit signalClientStatus(clientAddr, true);
        qDebug() << "New client connected:" << clientAddr;
    }
}

void TcpServer::slotReadyRead()
{
    QTcpSocket *clientSocket = qobject_cast<QTcpSocket *>(sender());
    if (clientSocket && clientSocket->bytesAvailable() > 0) {
        // 读取客户端数据
        QByteArray data = clientSocket->readAll();
        QString clientAddr = clientSocket->peerAddress().toString() + ":" +
                             QString::number(clientSocket->peerPort());

        // 发射“收到新数据”信号
        emit signalNewData(clientAddr, data);
        qDebug() << "Received from" << clientAddr << ": " << data;

        // （可选）向客户端回复数据
        clientSocket->write("Server received: " + data);
    }
}

void TcpServer::slotDisconnected()
{
    QTcpSocket *clientSocket = qobject_cast<QTcpSocket *>(sender());
    if (clientSocket) {
        // 从列表中移除并释放资源
        m_clientSockets.removeOne(clientSocket);
        QString clientAddr = clientSocket->peerAddress().toString() + ":" +
                             QString::number(clientSocket->peerPort());

        // 发射“客户端断开”信号
        emit signalClientStatus(clientAddr, false);
        qDebug() << "Client disconnected:" << clientAddr;

        clientSocket->deleteLater();
    }
}
